// pages/movie-list/movie-list.js
const qcloud = require('../../vendor/wafer2-client-sdk/index')
const config = require('../../config')
let page = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movieList: [],
    isLast: false,
    isLoading: false,
    searchKeys: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!this.data.isLoading) {
      page = 1;
      this.setData({
        searchKeys: ''
      })
      this.setData({
        movieList: []
      })
      this.getMovieList();
    }
  },

  /**
   * 每次添加评论之后返回该页面，由于电影评分变了，所以得刷新电影列表，所以在onShow中调用获取电影列表的函数
   */
  onShow() {
  },

  setInput(event) {
    console.log(event.detail)
    const { value, curor } = event.detail;
    this.setData({
      searchKeys: value
    })
  },

  /**
   * 搜索过滤电影列表
   */
  searchMovie() {
    if (!this.data.isLoading) {
      page = 1;
      this.setData({
        movieList: []
      })
      this.getMovieList();
    }
  },

  bindDownLoad: function () {
    //   该方法绑定了页面滑动到底部的事件
    if (!this.data.isLoading&&!this.data.isLast) {
      this.getMovieList();
    }
  },

  refresh: function (e) {
    if (this.data.isLoading) {
      return;
    }
    page = 1;
    this.setData({
      movieList: []
    });
    this.getMovieList();
  },

  /**
   * 获取电影列表
   * @param: cb 电影列表获取成功后执行的回调函数
   */
  getMovieList(cb) {
    let that = this;
    that.setData({
      isLoading: true
    })
    wx.showLoading({
      title: '加载电影列表中',
    })
    qcloud.request({
      url: config.service.movieList,
      data: {
        page,
        searchKeys: that.data.searchKeys
      },
      success: res => {
        wx.hideLoading();
        if (!res.data.code) {
          let addList = res.data.data ? res.data.data : [];
          if (addList.length >= 10) {
            page++;
            that.setData({
              isLast: false
            })
          } else {
            that.setData({
              isLast: true
            })
          }
          let movieList = that.data.movieList.concat(addList);
          console.log(movieList);
          console.log(res.data);
          movieList = movieList.map((movie) => {
            let temp = movie;
            temp.avgRating.toFixed(1);
            return temp;
          });
          that.setData({
            movieList
          })
          wx.showToast({
            title: '加载成功'
          });
        } else {
          wx.showToast({
            image: '../../images/error.png',
            title: '加载失败'
          });
        }
        
      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({
          image: '../../images/error.png',
          title: '加载失败'
        });
        console.log(err)
      },
      complete: () => {
        that.setData({
          isLoading: false
        })
        cb && cb();
      }
    })
  }
})